package v1

import (
	"sweetsunnyflower/app/models/user_follow"
	"sweetsunnyflower/app/policies"
	"sweetsunnyflower/app/requests"
	"sweetsunnyflower/pkg/auth"
	"sweetsunnyflower/pkg/response"

	"github.com/gin-gonic/gin"
)

type UserFollowsController struct {
	Controller
}

func (ctrl *UserFollowsController) Index(c *gin.Context) {
	userId := auth.CurrentIntUID(c)
	userFollows := user_follow.GetUserFollows(userId)
	response.Data(c, userFollows)
}

func (ctrl *UserFollowsController) Store(c *gin.Context) {

	request := requests.UserFollowRequest{}
	if ok := requests.Validate(c, &request, requests.UserFollowSave); !ok {
		return
	}

	user := auth.CurrentUser(c)

	// 查询当前用户是否已经关注了该用户
	isFollow, userFollowModel, err := user_follow.IsFollow(user.ID, request.FollowID)
	if err != nil {
		response.Abort500(c, err.Error())
		return
	}
	if isFollow {
		response.Created(c, userFollowModel)
		return
	}

	user.Follows = user.Follows + 1
	user.Save()

	userFollowModel = &user_follow.UserFollow{
		UserID:   user.ID,
		FollowID: request.FollowID,
	}

	userFollowModel.Create()

	if userFollowModel.ID > 0 {
		response.Created(c, userFollowModel)
	} else {
		response.Abort500(c, "创建失败，请稍后尝试~")
	}
}

func (ctrl *UserFollowsController) Delete(c *gin.Context) {

	userFollowModel := user_follow.Get(c.Param("id"))
	if userFollowModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyUserFollow(c, userFollowModel); !ok {
		response.Abort403(c)
		return
	}

	rowsAffected := userFollowModel.Delete()
	if rowsAffected > 0 {
		user := auth.CurrentUser(c)

		user.Follows = user.Follows - 1
		user.Save()

		response.Success(c)

		return
	} else {
		response.Abort500(c, "关注失败，请稍后尝试~")
		return
	}
}
